package com.yunji.framework_template.web.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.yunji.framework_template.biz.cache.CacheService;
import com.yunji.framework_template.biz.service.AppsService;
import com.yunji.framework_template.common.web.Page;
import com.yunji.framework_template.common.web.Result;
import com.yunji.framework_template.orm.datasource.HandleDataSource;
import com.yunji.framework_template.orm.persistence.model.Apps;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by fenglibin on 2018/12/12.
 */
@Slf4j
@Controller
@RequestMapping("/apps/")
public class AppsController {

    private static final String googlePlayUrl = "https://play.google.com/store/apps/details?id=";

    @Value("#{settings['system.domain']}")
    private String              systemDomain;

    @Autowired
    private AppsService         appsService;
    @Resource
    private CacheService        cacheService;

    @RequestMapping("selectAll")
    @ResponseBody
    public Result<List<Apps>> selectAll() {
        return Result.success(appsService.selectAll());
    }

    @RequestMapping("select")
    @ResponseBody
    public Result<Apps> selectByPrimaryKey(String packageName) {
        return Result.success(appsService.selectByPrimaryKey(packageName));
    }

    @RequestMapping("selectByCondition")
    @ResponseBody
    public Result<List<Apps>> selectByCondition(Apps record) {
        return Result.success(appsService.selectByCondition(record));
    }

    @RequestMapping("count")
    @ResponseBody
    public Result<Integer> count(Apps record) {
        return Result.success(appsService.count(record));
    }

    @RequestMapping("insert")
    @ResponseBody
    public Result<Integer> insertSelective(Apps record) {
        return Result.success(appsService.insertSelective(record));
    }

    @RequestMapping("update")
    @ResponseBody
    public Result<Integer> updateByPrimaryKeySelective(Apps record) {
        return Result.success(appsService.updateByPrimaryKeySelective(record));
    }

    @RequestMapping("selectByPage")
    @ResponseBody
    public Result<Page<List<Apps>>> selectByPage(Page<Apps> page) {
        List<Apps> list = null;
        page = page.sequentialDisplayCalculate(appsService.count(page.getObj()));
        if (page.getTotalCount() > 0) {
            list = appsService.selectByPage(page);
        }
        Page<List<Apps>> result = new Page<List<Apps>>(page, list);
        return Result.success(result);
    }

    @RequestMapping("deleteByCondition1")
    @ResponseBody
    public Result<Integer> deleteByCondition(Apps record) {
        return Result.success(appsService.deleteByCondition(record));
    }

    @RequestMapping("delete1")
    @ResponseBody
    public Result<Integer> deleteByPrimaryKey(String packageName) {
        return Result.success(appsService.deleteByPrimaryKey(packageName));
    }

    @RequestMapping("deleteIconIsNull")
    @ResponseBody
    public Result<Integer> deleteIconIsNull() {
        return Result.success(appsService.deleteIconIsNull());
    }

    @RequestMapping("loadApps")
    @ResponseBody
    public Result<?> loadApps(HttpServletRequest request) {
        String countryCode = request.getParameter("countryCode");
        String filePath = request.getParameter("filePath");
        new Thread() {

            public void run() {
                try {
                    HandleDataSource.putDataSource(countryCode);
                    appsService.loadAppsFromFile(countryCode, filePath);
                    appsService.getAppIconFromGooglePlay();
                } catch (IOException e) {
                    log.error("Load app exception heppened:" + e.getMessage(), e);
                }

            }
        }.start();

        return Result.success(null);
    }

    @RequestMapping("loadCountryApps")
    @ResponseBody
    public Result<?> loadCountryApps(HttpServletRequest request) {
        String countryCode = request.getParameter("countryCode");
        String getIcon = request.getParameter("getIcon");
        new Thread() {

            public void run() {
                try {
                    HandleDataSource.putDataSource(countryCode);
                    appsService.loadAppsFromAppAnnie(countryCode);
                    if ("true".equals(getIcon)) {
                        appsService.getAppIconFromGooglePlay();
                    }
                } catch (IOException e) {
                    log.error("Load app exception heppened:" + e.getMessage(), e);
                }

            }
        }.start();

        return Result.success(null);
    }

    @RequestMapping("getAppIconFromGooglePlay")
    @ResponseBody
    public Result<?> getAppIconFromGooglePlay(HttpServletRequest request) {
        String countryCode = request.getParameter("countryCode");
        new Thread() {

            public void run() {
                HandleDataSource.putDataSource(countryCode);
                appsService.getAppIconFromGooglePlay();

            }
        }.start();

        return Result.success(null);
    }

    /**
     * Home page
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws HttpException,
                                                                                        IOException {
        log.info("Apps index is accessed.");
        ModelAndView view = new ModelAndView("apps/apps_index");
        view.getModelMap().addAttribute("indexType", "Apps");
        view.getModelMap().addAttribute("systemDomain", systemDomain);

        return view;
    }

    // RequestMapping中忽略扩展名，见文章:https://www.cnblogs.com/moonandstar08/p/7078263.html
    @RequestMapping(value = "/go/{packageName:.+}", method = RequestMethod.GET)
    public ModelAndView go(@PathVariable("packageName") String packageName) throws HttpException, IOException {
        log.info("Access package name is:" + packageName);
        Apps apps = appsService.selectByPrimaryKey(packageName);
        if (apps == null) {
            log.warn("Cannot get apps by package name:" + packageName);
        } else {
            appsService.addViewsByPrimaryKey(apps);
        }
        return new ModelAndView(new RedirectView(googlePlayUrl + packageName));
    }

}
